<?php
// +----------------------------------------------------------------------

// | FeelCRM开源客户管理系统

// +----------------------------------------------------------------------

// | 欢迎阅读学习系统程序代码，您的建议反馈是我们前进的动力

// | 开源版本仅供技术交流学习，请务必保留界面版权logo

// | 商业版本务必购买商业授权，以免引起法律纠纷

// | 禁止对系统程序代码以任何目的，任何形式的再发布

// | gitee下载：https://gitee.com/feelcrm_gitee

// | github下载：https://github.com/feelcrm-github

// | 开源官网：https://www.feelcrm.cn

// | 成都菲莱克斯科技有限公司 版权所有 拥有最终解释权

// +----------------------------------------------------------------------

namespace Index\Controller;

use Crypto\CryptMessage;
use Index\Common\BasicController;

class GroupController extends BasicController
{
	protected static $_filter = ['group_name','manager_id','ticket_auth','crm_auth','orderby','is_default','closed'];


	public function _initialize()
    {
        parent::_initialize(); // TODO: Change the autogenerated stub

        $members = D('Member')->where(['company_id'=>$this->_company_id,'type'=>1,'closed'=>0])->field('member_id,name')->fetchAll();

        $this->assign('members',$members);
    }


//    部门列表
	public function index($request = '',$page = 300,$keyword = '')
	{
        if(IS_AJAX)
        {
            if($request == 'assign')
            {
                $count = M('member')->where(['company_id'=>$this->_company_id,'type'=>1])->count('member_id');

                $Page = new \Think\Page($count, $page);

                $member = M('member')->where(['company_id'=>$this->_company_id,'type'=>1])
                    ->field('member_id,group_id,name,mobile,email')
                    ->limit($Page->firstRow, $Page->listRows)->select();

                $result = ['data'=>$member,'pages'=>ceil($count/$page)];
            }
            else if($request == 'submit')
            {
                $userIds = I('post.userId');

                $group_id = I('get.id');

                if(!M('group')->where(['group_id'=>$group_id,'company_id'=>$this->_company_id])->getField('group_id'))
                {
                    $result = ['errcode'=>2,'msg'=>L('SELECT_SECTOR')];
                }
                else if(!$userIds)
                {
                    $result = ['errcode'=>2,'msg'=>L('SELECT_USER')];
                }
                else
                {
                    $members = M('member')->where(['company_id'=>$this->_company_id,'type'=>1,'member_id'=>['in',$userIds]])->field('member_id,group_id')->select();

                    foreach($members as $v)
                    {
                        $groupIds = explode(',',$v['group_id']);

                        if(!in_array($group_id,$groupIds))
                        {
                            if(!$v['group_id'])
                            {
                                $groupId = $group_id;
                            }
                            else
                            {
                                $groupId = $v['group_id'].','.$group_id;
                            }

                            M('member')->where(['member_id'=>$v['member_id']])->setField(['group_id'=>$groupId]);
                        }
                    }

                    $notInMember = M('member')
                        ->where(['company_id'=>$this->_company_id,'type'=>1,'member_id'=>['not in',$userIds],"find_in_set('{$group_id}',group_id)"])
                        ->field('member_id,group_id')
                        ->select();

                    foreach($notInMember as $nv)
                    {
	                    $groupId = explode(',',$nv['group_id']);

	                    $groupIds = '';

	                    foreach($groupId as $k=>$v)
	                    {
		                    if($group_id != $v)
		                    {
			                    $groupIds = $v.',';
		                    }
	                    }

                        M('member')->where(['member_id'=>$nv['member_id']])->setField(['group_id'=>rtrim($groupIds,',')]);
                    }

                    $result = ['errcode'=>0,'msg'=>L('UPDATE_SUCCESS'),'isReload'=>1];
                }
            }
            else
            {
                $result = ['errcode'=>2,'msg'=>L('ILLEGAL')];
            }

            $this->ajaxReturn($result);
        }
        else
        {
            $where = [];

	        if($keyword)
	        {
		        $where = ['company_id'=>$this->_company_id,'group_name'=>['LIKE','%'.$keyword.'%']];

		        $ids = M('Group')->where($where)->field('group_id')->order('group_id asc')->select();

		        $values = array_column($ids,'group_id');
	        }
	        else
	        {
		        $ids = $values = [];
	        }

	        $where['company_id'] = $this->_company_id;

	        $departments = M('Group')->where($where)->field('group_id,parent_id,group_name,manager_id,orderby,closed')->order('orderby asc')->select();

	        foreach($ids as $key=>$val)
	        {
		        $parentIds = D('Group')->getParentIds($departments,$val['group_id']);

		        $values = array_unique(array_merge($values,$parentIds));
	        }

	        foreach($departments as &$v)
	        {
		        $v['manager'] = M('member')->where(['member_id'=>$v['manager_id']])->field('name,face')->find();
	        }

	        $department = $this->getTreeHtml(fetchAll($departments,'group_id'),0,'group_id',1,$values);

//            权限 - 新增部门
	        $auth['create'] = D('RoleAuth')->checkRoleAuthByMenu($this->_company_id,'group/create',$this->_member['role_id']);

//            权限 - 修改部门
	        $auth['editor'] = D('RoleAuth')->checkRoleAuthByMenu($this->_company_id,'group/editor',$this->_member['role_id']);

//            权限 - 删除部门
	        $auth['delete'] = D('RoleAuth')->checkRoleAuthByMenu($this->_company_id,'group/delete',$this->_member['role_id']);

//            权限 - 用户列表
	        $auth['member'] = D('RoleAuth')->checkRoleAuthByMenu($this->_company_id,'member/index',$this->_member['role_id']);

//            权限 - 项目列表
	        $auth['project'] = D('RoleAuth')->checkRoleAuthByMenu($this->_company_id,'project/index',$this->_member['role_id']);

	        $data = ['department'=>$department,'auth'=>$auth,'groups'=>json_encode($departments)];
//getPrint($data);die;
	        $this->assign('data',$data);

	        $this->assign('keyword',$keyword);

            $this->display();
        }
	}


//    添加部门
	public function create()
	{
		if(IS_POST)
		{
			$data = $this->checkRequestData();

			$group_id = M('group')->add($data);

			if($group_id > 0)
			{
				if($data['is_default'] == 20)
				{
					M('Group')->where(['company_id'=>$this->_company_id,'is_default'=>20,'group_id'=>['neq',$group_id]])->save(['is_default'=>10]);
				}

				saveFeelDeskEncodeId($this->_company_id,$group_id,'Group');

				$this->updateMemberGroup($group_id,$data['manager_id']);

				$result = ['status'=>2,'msg'=>L('SUBMIT_SUCCESS'),'url'=>U('index'),'reloadType'=>'parent'];
			}
			else
			{
				$result = ['status'=>0,'msg'=>L('SUBMIT_FAILED')];
			}

            $this->ajaxReturn($result);
		}
		else
		{
			$department = M('group')
				->where(['company_id'=>$this->_company_id])
				->field('group_id,group_name,parent_id')
				->select();

			$department = getSubjectTree($department,'group_id','parent_id','child');

			$members = M('member')
				->where(['company_id'=>$this->_company_id,'type'=>1,'closed'=>0])
				->field('member_id,name')
				->select();

			$this->assign('members',$members);

			$this->assign('jsonDepartmentData',json_encode($department));

			$this->display();
		}
	}


//    编辑部门
	public function editor($id = '')
	{
		$group_id = decrypt($id,'GROUP');

		if(!$detail = M('Group')->where(['group_id'=>$group_id,'company_id'=>$this->_company_id])->find())
		{
			$this->returnError(L('GROUP_NOT'),U('Index/welcome'));
		}

		if(IS_POST)
		{
			$data = $this->checkRequestData('editor',$group_id);

			$data['group_id'] = $group_id;

//		      查询是否为默认部门
			$is_default = M('group')->where(['group_id'=>$group_id])->getField('is_default');

			$result = M('group')->save($data);

			if($result !== false)
			{
				if($detail['manager_id'] != $data['manager_id'])
				{
//				    更新部门管理员所属部门
					$this->updateMemberGroup($group_id,$data['manager_id']);
				}

//				更新子级层级
				D('Group')->updateChildLevel($group_id,$data['level']);

				if($data['is_default'] == 20 && $is_default == 10)
				{
					M('Group')->where(['company_id'=>$this->_company_id,'is_default'=>20,'group_id'=>['neq',$group_id]])->save(['is_default'=>10]);
				}

				$result = ['status'=>2,'msg'=>L('UPDATE_SUCCESS'),'url'=>U('index'),'reloadType'=>'parent'];
			}
			else
			{
				$result = ['status'=>0,'msg'=>L('UPDATE_FAILED')];
			}

			$this->ajaxReturn($result);
		}
		else
		{
			$departments = M('group')
				->where(['company_id'=>$this->_company_id])
				->field('group_id,group_name,parent_id')
				->select();

			$selected = D('Group')->getParentIds($departments,$group_id);

			$members = M('member')
				->where(['company_id'=>$this->_company_id,'type'=>1,'closed'=>0])
				->field('member_id,name')
				->select();

			$departments = getSubjectTree($departments,'group_id','parent_id','child');

			$this->assign('jsonDepartmentData',json_encode($departments));

			$this->assign('selected',json_encode($selected));

			$this->assign('members',$members);

			$this->assign('detail',$detail);

			$this->display();
		}
	}


	private function checkRequestData($source = '',$group_id = 0)
	{
		$data = checkFields(I('post.data'), self::$_filter);

		if(empty($data['group_name']))
		{
			$this->ajaxReturn(['status'=>0,'msg'=>L('ENTER_SECTOR_NAME')]);
		}

        if(empty($data['manager_id']))
        {
            $this->ajaxReturn(['status'=>0,'msg'=>L('SELECT_GROUP_MANAGER')]);
        }

        if(!$data['ticket_auth'] && !$data['crm_auth'])
        {
            $this->ajaxReturn(['status'=>0,'msg'=>L('SELECT_SYSTEM_AUTH')]);
        }

		$parent_id = I('post.parent_id');

		if($parent_id)
		{
			$level = count(explode(',',trim($parent_id,',')))+1;
		}
		else
		{
			$level = 1;
		}

		$parent_id = end(explode(',',trim($parent_id,',')));

		if($data['closed'] == 1 && $data['is_default'] == 20)
		{
			$this->ajaxReturn(['status'=>0,'msg'=>L('CLOSE_GROUP_NOTE')]);
		}

		$data['ticket_auth'] = $data['ticket_auth'] == 'on' ? 10 : 20;

		$data['crm_auth'] = $data['crm_auth'] == 'on' ? 10 : 20;

		if($source == 'editor')
		{
			if($group_id && $parent_id == $group_id)
			{
				$this->ajaxReturn(['status'=>0,'msg'=>L('MENU_NOTE4')]);
			}

			if($parent_id)
			{
				$departments = M('group')
					->where(['company_id'=>$this->_company_id])
					->field('group_id,group_name,parent_id')
					->select();

				$selected = D('Group')->getParentIds($departments,$parent_id);

				if($selected && in_array($group_id,$selected))
				{
					$this->ajaxReturn(['status'=>0,'msg'=>'不能选择子级部门作为上级部门']);
				}
			}

//		    必须保留一个默认部门
			if($data['is_default'] == 10)
			{
				$has_default = M('Group')->where(['company_id'=>$this->_company_id,'is_default'=>20,'group_id'=>['neq',$group_id]])->getField('group_id');

				if(!$has_default)
				{
					$this->ajaxReturn(['status'=>0,'msg'=>L('DEFAULT_GROUP_NOTE1')]);
				}
			}

			$result = [
				'parent_id'  => $parent_id ? $parent_id : 0,
				'manager_id' => $data['manager_id'],
				'group_name' => $data['group_name'],
				'ticket_auth'=> $data['ticket_auth'],
				'crm_auth'	 => $data['crm_auth'],
				'orderby'    => (int) $data['orderby'] ? (int) $data['orderby'] : 100,
				'level'      => $level,
				'is_default' => $data['is_default'],
				'closed'     => $data['closed'],
			];
		}
		else
		{
			$result = [
				'company_id' => $this->_company_id,
				'parent_id'  => $parent_id ? $parent_id : 0,
				'manager_id' => $data['manager_id'],
				'group_name' => $data['group_name'],
				'ticket_auth'=> $data['ticket_auth'],
				'crm_auth'	 => $data['crm_auth'],
				'orderby'    => (int) $data['orderby'] ? (int) $data['orderby'] : 100,
				'level'      => $level,
				'is_default' => $data['is_default'],
				'closed'     => $data['closed'],
				'create_ip'  => get_client_ip(),
				'create_time'=> NOW_TIME
			];
		}

		return $result;
	}


	private function updateMemberGroup($group_id,$member_id)
    {
        $groupIds = M('member')->where(['member_id'=>$member_id])->getField('group_id');

        $groupIds = explode(',',$groupIds);

        if(!in_array($group_id,$groupIds))
        {
            array_push($groupIds,$group_id);
        }

        M('member')->save(['member_id'=>$member_id,'group_id'=>implode(',',$groupIds)]);
    }


    public function delete()
    {
        $data = I('post.group');

//	    $data['group_id'] = decrypt($data['group_id'],'GROUP');

        if(!$detail = M('Group')->where(['group_id'=>$data['group_id'],'company_id'=>$this->_company_id])->find())
        {
	        $result = ['errcode'=>1,'msg'=>L('SECTOR_NOT')];
        }
        else if(M('Group')->where(['parent_id'=>$data['group_id']])->getField('group_id'))
        {
	        $result = ['status'=>0,'msg'=>L('DELETE_DEPARTMENT_NOTE')];
        }
        else if(!M('Group')->where(['group_id'=>$data['update_group_id'],'company_id'=>$this->_company_id])->getField('group_id'))
        {
	        $result = ['errcode'=>1,'msg'=>L('SECTOR_NOT')];
        }
        else if(empty($data['update_group_id']))
        {
	        $result = ['errcode'=>1,'msg'=>L('SELECT_SECTOR')];
        }
        else
        {
	        $result = D('Group')->deleteGroup($this->_company_id,$detail,$data['update_group_id']);
        }

	    $this->ajaxReturn($result);
    }


	private function getTreeHtml($data,$parent_id,$pk,$level = 1,$values = [])
	{
		$html = $style = '';

		$editorAuth = D('RoleAuth')->checkRoleAuthByMenu($this->_company_id,'Group/editor',$this->_member['role_id']);

		$deleteAuth = D('RoleAuth')->checkRoleAuthByMenu($this->_company_id,'Group/delete',$this->_member['role_id']);

		foreach($data as $k => $v)
		{
			if(getTreeChild($data,$v['group_id']))
			{
				$i = "<i class='iconfont icon-rights'></i> <i class='iconfont icon-dir-close'></i>";

				$padding = $level * 20;

//				默认展开的值
				if(in_array($v['group_id'],$values))
				{
					$i = "<i class='iconfont icon-rights icon-downs'></i> <i class='iconfont icon-dir-open'></i>";
				}
			}
			else
			{
				$i = "<i class='iconfont icon-dir-close color-ffe792'></i>";

				$padding = $level * 22;
			}

			if($v['parent_id'] == $parent_id)
			{
				$hide = '';

				if($level > 1 && !in_array($v['parent_id'],$values))
				{
					$hide = "style='display:none'";
				}

				$face = $v['manager']['face'] ? $v['manager']['face'] : '/Attachs/face/face.png';

				$html .= "<div class='department-item' data-id='{$v['group_id']}' data-pid='{$parent_id}' $hide>";

				$html .= "<div class='department-box'><div class='department-name' style='padding-left:{$padding}px'>{$i}<span>{$v['group_name']}</span></div>";

				$html .= "<div class='manager'><img src='{$face}' alt=''><span>{$v['manager']['name']}</span></div>";

				$html .= "<div class='operate'>";

				if($editorAuth)
				{
					$url = U('editor',['id'=>encrypt($v['group_id'],'GROUP')]);

					$html .= "<a href='javascript:' class='iconfont icon-editor' title='".L('EDITOR')."' onclick='openFormWindow(this,\"{$url}\")'></a>";
				}

				if($deleteAuth)
				{
					$url = U('delete',['id'=>$v['group_id']]);

					$html .= "<a href='{$url}' load='del-group' class='iconfont icon-member-delete'></a>";
				}

				$html .= "</div></div>";

				$html .= $this->getTreeHtml($data,$v[$pk],$pk,$level+1,$values);

				$html .= "</div>";
			}
		}

		return $html;
	}

}
